package com.sanploy.file.util;

import com.sanploy.file.dto.FoldToType;
import com.sanploy.file.enums.Compress;
import com.sanploy.file.enums.FileType;
import com.sanploy.file.vo.FileVo;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2017/4/7.
 */
public class FileUtil {

    private static List<String> foldList = new ArrayList<>();

    public static String fold;

    public static String creatUUID() {
        return UUID.randomUUID().toString();
    }

    public static FileVo uploadFile(MultipartFile file, String path) {
        String uuid = creatUUID();
        String suffix = file.getOriginalFilename().split("\\.")[file.getOriginalFilename().split("\\.").length - 1];
        File saveFile = new File(FileUtil.fold + path, uuid + "." + suffix);
        pathIsExist(saveFile);
        return new FileVo(FileType.NORMAL, file.getOriginalFilename(),
                save(path + File.separator + uuid + "." + suffix, saveFile, file),
                uuid + suffix);
    }

    public static FileVo uploadImgToJpg(MultipartFile file, String path) {
        if (ImageUtil.isPicture(file.getOriginalFilename())) {

            String uuid = creatUUID();
            String suffix = ".jpg";
            File saveFile = new File(FileUtil.fold + path, uuid + suffix);
            pathIsExist(saveFile);
            return new FileVo(FileType.ORIGIN, file.getOriginalFilename(), save(path + uuid + suffix, saveFile, file),
                    uuid + suffix);
        }
        return null;
    }


    public static List<FileVo> uploadShowImgToJpg(MultipartFile file, String path, FoldToType[] dir) {
        List<FileVo> list = new ArrayList<>();
        if (ImageUtil.isPicture(file.getOriginalFilename())) {
            String uuid = creatUUID();
            String suffix = ".jpg";
            FileVo originFile = null;
            for (FoldToType item : dir) {
                if (!item.isChange()) {
                    File saveFile = new File(FileUtil.fold + path+ File.separator + item.getFold() , uuid + suffix);
                    pathIsExist(saveFile);
                    originFile = new FileVo(item.getFileType(), file.getOriginalFilename(),
                            save(path + item.getFold() + File.separator + uuid + suffix, saveFile, file), uuid + suffix);
                    list.add(originFile);
                } else {
                    list.add(new FileVo(item.getFileType(), file.getOriginalFilename(),
                            ImageUtil.changeImgSize(originFile.getSavePath(), path +
                                     item.getFold() + File.separator + originFile.getNewName(), item.getWidth(), item.getHigh())));
                }
            }
            return list;
        }
        return null;
    }

    public static String compressImage(String src, String target, int width, int height, String compress) throws IOException {
        switch (Compress.valueOf(compress)) {
            case FORCE:
                ImageUtil.changeImgSize(src, target, width, height);
                break;
            case RATIO:
                ImageUtil.changeImgSizeRatio(src, target, width, height);
                break;
        }
        return target;
    }


    private static String save(String savePath, File saveFile, MultipartFile file) {
        byte[] bytes;
        try {
            bytes = file.getBytes();
            BufferedOutputStream bufferedOutputStream =
                    new BufferedOutputStream(new FileOutputStream(saveFile));
            bufferedOutputStream.write(bytes);
            bufferedOutputStream.close();

            String savepaths = File.separator + savePath;
            savepaths = savepaths.replaceAll(File.separator+File.separator,"/");
            return savepaths;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getJarDir() {
        File file = getFile();
        if (file == null)
            return null;
        return getFile().getParent();
    }

    /**
     * 获取当前Jar文件
     *
     * @return
     */
    public static File getFile() {
        // 关键是这行...
        String path = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile();
        try {
            path = java.net.URLDecoder.decode(path, "UTF-8"); // 转换处理中文及空格
        } catch (java.io.UnsupportedEncodingException e) {
            return null;
        }
        return new File(path);
    }

    public static void pathIsExist(String path) {
        File fold = new File(path);
        String dir = "";
        if (path.contains(".")) {
            dir = fold.getParent();
        } else {
            dir = fold.getPath();
        }
        fold = new File(dir);
        if (!fold.exists()) {
            fold.mkdirs();
        }
        fold.setReadable(true);
        fold.setWritable(true);
    }


    /**
     * 获取文件的目录
     *
     * @param filePath
     * @return
     */
    public static String getFilePath(String filePath) {
        File file = new File(filePath);
        try {
            return file.getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void pathIsExist(File fold) {
        String dir = "";
        if (fold.getPath().contains(".")) {
            dir = fold.getParent();
        } else {
            dir = fold.getPath();
        }
        fold = new File(dir);
        if (!fold.exists()) {
            fold.mkdirs();
        }
        fold.setReadable(true);
        fold.setWritable(true);
    }


    /**
     * 扫描一级文件夹
     *
     * @param path
     */
    public static void scanFirstFold(String path) {
        //win下
        path = path.replaceAll("file:\\\\","");
        //Linux下
        path = path.replaceAll("file:","");
        System.out.println("scanFirstFold:"+path);

        fold = path;
        Optional.ofNullable(new File(path).getAbsoluteFile().list()).
                ifPresent((fileList) -> foldList.addAll(Arrays.asList(fileList)));
        foldList.forEach(System.out::println);
    }

    /**
     * 创建一级目录
     */
    public static void creatFirstFold(String name) {
        pathIsExist(fold + name);
        foldList.add(name);
    }

    /**
     * 获取一级目录文件名
     */
    public static List<String> getFirstFold() {
        return foldList;
    }

    /**
     * 文件夹是否包含此项目名
     *
     * @param foldName 文件夹名
     * @return
     */
    public static boolean isContainsProject(String foldName) {
        return foldList.contains(foldName);
    }

}
